﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
using System.Xml;
using Javavaj.iHunter;
using Javavaj.iHunter.Core;

namespace Javavaj.iHunter.RssChannels
{
    public class RssChannel : IChannel
    {
        private string title;
        private string uri;
        private string description = "";

        public RssChannel(string title, string uri)
        {
            if (title != "")
                this.title = title;
            else
                this.title = uri;
            this.uri = uri;
        }

        #region IChannel Members

        public string Title
        {
            get
            {
                return title;
            }
        }

        public string Category
        {
            get
            {
                return "RSS";
            }
        }

        public string Link
        {
            get
            {
                return uri;
            }
        }

        public string Description
        {
            get
            {
                return description;
            }
        }

        public bool Open()
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            StreamReader sr = null;
            XmlDocument xml = null;
            try
            {
                request = (HttpWebRequest)WebRequest.Create(uri);
                request.Method = "GET";
                response = (HttpWebResponse)request.GetResponse();
                sr = new StreamReader(response.GetResponseStream());
                xml = new XmlDocument();
                xml.LoadXml(sr.ReadToEnd());
            }
            catch
            {
                if (response != null)
                    response.Close();
                if (sr != null)
                    sr.Close();
                return false;
            }
            try
            {
                description = xml.DocumentElement["channel"]["description"].InnerText;
            }
            catch
            {
                description = "";
            }
            return true;
        }

        public void Close()
        {
            //nothing to do;
        }

        public DateTime LastUpdateTime
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }


        public override int GetHashCode()
        {
            return (Category + uri).GetHashCode();
        }

        public ICollection<IMessage> GetMessages(DateTime startTime, DateTime endTime, string category)
        {
            List<IMessage> messages = new List<IMessage>();
                       
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            StreamReader sr = null;
            XmlDocument xml = null;
            
            try
            {
                request = (HttpWebRequest)WebRequest.Create(uri);
                request.Method = "GET";
                response = (HttpWebResponse)request.GetResponse();
                sr = new StreamReader(response.GetResponseStream());
                xml = new XmlDocument();
                xml.LoadXml(sr.ReadToEnd());

                foreach (XmlElement ele in xml.DocumentElement["channel"].GetElementsByTagName("item"))
                {
                    if (ele["pubDate"] == null || DateTime.Parse(ele["pubDate"].InnerText) >= startTime && DateTime.Parse(ele["pubDate"].InnerText) <= endTime)
                    {
                        Message msg = new Message(this);

                        if (ele["title"] != null)
                            msg.Title = ele["title"].InnerText;

                        if (ele["author"] != null)
                            msg.Author = ele["author"].InnerText;

                        if (ele["category"] != null)
                            msg.Category = ele["category"].InnerText;

                        if (ele["link"] != null)
                            msg.Link = ele["link"].InnerText;

                        if (ele["description"] != null)
                            msg.Content = ele["description"].InnerText;

                        if (msg.Link != "")
                            msg.Content += "<br><br>Link: <a href = \"" + msg.Link + "\">" + msg.Link + "</a>";

                        msg.ContentType = "html";

                        if (ele["pubDate"] != null)
                            msg.PubTime = DateTime.Parse(ele["pubDate"].InnerText);

                        if (ele["guid"] != null)
                            msg.Uid = ele["guid"].InnerText.GetHashCode();
                        else if (ele["link"] != null)
                            msg.Uid = ele["link"].InnerText.GetHashCode();
                        else
                            msg.Uid = (msg.Title + (string)msg.Content).GetHashCode();

                        messages.Add(msg);
                    }
                }
            }
            catch
            {
                if (response != null)
                    response.Close();
                if (sr != null)
                    sr.Close();
            }

            return messages;
        }

        public Stream DownloadFile(IFileObject file)
        {
            return null;
        }

        public bool RefreshMessage(IMessage message)
        {
            //always the same as the old message, so return false
            return false;
        }

        public void NotifyReply(IMessage source)
        {
            //nothing to do
        }

        public bool Reply(IMessage source, IDictionary<string, object> replyinput, string tag)
        {
            //nothing to do
            return false;
        }

        public event EditReplyEventHandler EditReply;

        #endregion
    }
}
